import Vue from 'vue'
import Vuex from 'vuex'
import config from "@/config";

import {
	login
} from '@/api/login.js'
import {
	getClientInfo
} from '@/api/mine.js'
import {
	getAdGoods
} from '@/api/goods.js'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token: uni.getStorageSync('token'),
		userInfo: uni.getStorageSync('userInfo'),
		sysToken: uni.getStorageSync('sysToken'),
		sysUserInfo: uni.getStorageSync('sysUserInfo'),
		requestLoading: false, //加载等待是否显示,
		shopId: '',
		invitationCode: '', //邀请码
		adGoods: [],
		location: {},
		userPoints: 0,
		partnerInfo: {
			name: '',
			sex: '',
			birthday: '',
			mobile: '',
			status: 1, //1: 新增， 2：支付  3:已过期
			address: '',
			city: '',
			type: 1, //1-普通合伙人 2-城市合伙人 3-战略合伙人
		},
		// discountRate: 10,

		device: {}, //设备信息，以像素为单位
	},
	mutations: {
		SET_INVITATION_CODE: (state, data) => {
			uni.setStorageSync('invitationCode', data)
			state.invitationCode = data;
		},
		SET_LOCATION: (state, data) => {
			uni.setStorageSync('location', data)
			state.location = data;
		},
		//客户端
		setToken: (state, data) => {
			uni.setStorageSync('token', data)
			state.token = data;
		},
		SET_USER_INFO: (state, data) => {
			uni.setStorageSync('userInfo', data);
			state.userInfo = data;
			// state.discountRate = data.discountRate;
		},
		CLEAR_CLIENT_USER_INFO:(state) =>{
			console.log("clearClientUserInfo state=", state)
			uni.removeStorageSync('userInfo')
			state.userInfo = null;
			
			uni.removeStorageSync('token')
			state.token = null;
			
		},
		
		setSysUserInfo: (state, data) => {
			uni.setStorageSync('sysUserInfo', data);
			state.sysUserInfo = data;
		},
		removeInfo: (state, data) => {
			uni.removeStorageSync('sysToken');
			uni.removeStorageSync('sysUserInfo');
			state.sysToken = null;
			state.sysUserInfo = null;
		},

		request_show_loading(state) {
			state.requestLoading = true;
		},
		//隐藏请求加载动画
		request_hide_loading(state) {
			state.requestLoading = false;
		},
		ADD_ADGOODS(state, data) {
			state.adGoods = data;
		},
		
		SET_DEVICE_INFO(state, device) {
			state.device = device
		},
		SET_SYS_TOKEN: (state, data) => {
			uni.setStorageSync('sysToken', data.authorization);
			state.sysToken = data.authorization;
		},
		
	},
	actions: {
		clearClientUserInfo({commit}){
			commit('CLEAR_CLIENT_USER_INFO')
		},
		getClientInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getClientInfo().then(res => {
					console.log("getClientInfo res=", res)
					// commit('SET_USER_INFO', res)
					if(res) {
						commit('SET_USER_INFO', res)
					} else {
						// 找不到该用户
						commit('CLEAR_CLIENT_USER_INFO')
					}
					resolve(true)
				}).catch(err => {})
			})
		},
		
		updateUserInfo({
			commit
		}, info) {
			console.log(info)
			commit('SET_USER_INFO', info)
		},
		getAdGoods({
			commit
		}) {
			getAdGoods().then(res => {
				commit('ADD_ADGOODS', res)
			})
		},
		

		setDeviceInfo(context) {
			const sys = wx.getSystemInfoSync()
			// 判断是否是带有刘海的全面屏设备
			let isNotchScreen = sys.safeArea && sys.safeArea.top > 20
			console.log((isNotchScreen ? 'NotchScreen' : 'not notch screen') + ", sys=", sys)
			let device = {}
			device.statusBarHeight = sys.statusBarHeight //状态栏高度
			device.screenWidth = sys.screenWidth //屏幕宽度
			device.screenHeight = sys.screenHeight //屏幕高度
			device.windowHeight = sys.windowHeight //可视区域高度
			// device.statusBarHeight = sys.statusBarHeight //20 或 44
			device.navigationBarHeight = 44 + sys.statusBarHeight //导航栏高度
			device.tabBarHeight = isNotchScreen ? 83 : 49 //底部tabBar高度
			device.bottomHeight = isNotchScreen ? 34 : 0 //底部刘海屏高度
			device.customBottomHeight = isNotchScreen ? 14 : 0 //自定义底部高度
			device.isNotchScreen = isNotchScreen //是否是刘海屏
			device.footerHeight = isNotchScreen ? 63 : 49 //底部footer高度 
			context.commit('SET_DEVICE_INFO', device)
			console.log("**device=", device)
		},
		login({
			commit,
			dispatch
		}) {
			return new Promise((resolve, rej) => {
				uni.showLoading({
					// mask: true
				})
				uni.getUserProfile({
					desc: '登陆',
					lang: 'zh_CN',
					fail: f => {
						console.log('fail', f)
						uni.hideLoading();
						// uni.showToast({
						// 	title:'取消登陆',
						// 	icon:'none'
						// })
					},
					success: infoRes => {
						console.log("infoRes=", infoRes)
						const {
							encryptedData,
							iv
						} = infoRes;
						uni.login({
							provider: 'weixin',
							success: loginRes => {
								const code = loginRes.code;
								var invitationCode = store.state
									.invitationCode || '';
								const params = {
									code,
									encryptedData,
									iv,
									invitationCode
								}
								uni.request({
									url: config.baseApi +
										'/customer/mine/login',
									data: params,
									method: 'POST',
									header: {
										'content-type': 'application/json' //自定义请求头信息
									},
									success: (res) => {
										if (res.data.httpCode ==
											200) {
											commit('SET_USER_INFO',
												res.data.data)
											commit('setToken', res
												.data.data
												.authorization)
											const pages =
												getCurrentPages()
											const curPage = pages[
												pages.length - 1
												]
											dispatch('getAdGoods');
											dispatch(
												'getClientInfo')
											// 声明一个当前页面
											curPage.onLoad(curPage
													.options
													) // 传入参数
											curPage.onShow()
											curPage.onReady()
											resolve(true);
										}
									},
									complete: () => {
										uni.hideLoading()
									},
									fail: f => {
										rej(f)
									}
								});
							}
						})
					}
				})

			})


		},
		getLocation({
			commit
		}) {
			console.log('address')
			uni.showModal({
				cancelText: "取消", // 取消按钮的文字  
				confirmText: "确认", // 确认按钮文字 
				title: '授权提示',
				content: '需要查看您的地理位置获取附近店铺?',
				confirmColor: '#3B8BFF',
				cancelColor: '#222222',
				success: res => {
					uni.getLocation({
						success: res => {
							commit('SET_LOCATION', res)
							const pages = getCurrentPages()
							const curPage = pages[pages.length - 1]
							// 声明一个当前页面
							curPage.onLoad(curPage.options) // 传入参数
							curPage.onShow()
							curPage.onReady()
						},

						fail: err => {
							console.log('err', err)
							uni.showToast({
								icon: 'none',
								title: '获取位置失败',
							})
						}
					})
				},
			})
		}
	}
})

export default store;